/*
-----------------
Unicorn Princess
Iteration 1
Rachel J. Morris
www.moosader.com
Dec 2009-Feb 2010
-----------------

SoundManager.cpp
*/

#include "SoundManager.h"

SoundManager::~SoundManager()
{
    Destroy();
}

void SoundManager::Destroy()
{
    Mix_CloseAudio();
    if ( inst != NULL )
        delete [] inst;
}

// Singleton intialization accessors
SoundManager& SoundManager::GetInst()
{
    if ( !inst )
        inst = new SoundManager();

    return *inst;
}

SoundManager* SoundManager::InstPtr()
{
    if ( !inst )
        inst = new SoundManager();

    return inst;
}

// Initialization / Constructors / Destructors

void SoundManager::Init( string& sndDir )
{
    /* For each Image (class) type, initialize based on it's index */
    int i;
    for ( i=0; i<SNDAMT; i++ )
    {
        sound[i].Init( i, sndDir );
    }
    for ( i=0; i<MSCAMT; i++ )
    {
        music[i].Init( i, sndDir );
    }
}

// Sound functions
void SoundManager::PlaySound( int iID )
{
    // Mix_PlayChannel( channel, sound, loop )
    // Channel = -1 for first available channel.  Loop = 0 for false
    Mix_PlayChannel( -1, sound[iID].snd, false );
}

void SoundManager::PlaySound( const string& szID )
{
    PlaySound( ReturnIntId( szID, false ) );
}

void SoundManager::PlayMusic( int iID )
{
    // Mix_PlayMusic( music, loop )
    // Since loop = -1, it will loop until stopped manually.
    Mix_PlayMusic( music[iID].msc, -1 );
}

void SoundManager::PlayMusic( const string& szID )
{
    PlayMusic( ReturnIntId( szID, true ) );
}

void SoundManager::PauseMusic()
{
    Mix_PauseMusic();
}

void SoundManager::ResumeMusic()
{
    Mix_ResumeMusic();
}

void SoundManager::StopMusic()
{
    Mix_HaltMusic();
}

// Misc functions

int SoundManager::ReturnIntId( string szID, bool isMusic )
{
    int i = 0;
    bool searching = true;

    /* Search for image integer IDs with same string ID as what was given */
    if ( isMusic )
    {
        // Searching for a Music object
        while ( i < MSCAMT && searching )
        {
            if ( music[i].StrID() == szID )
                searching = false;
            else
                i++;
        }

        if ( searching == true )    // it wasn't found
            i = -1;

    }
    else
    {
        // Searching for a Sound object
        while ( i < SNDAMT && searching )
        {
            if ( sound[i].StrID() == szID )
                searching = false;
            else
                i++;
        }

        if ( searching == true )    // it wasn't found
            i = -1;
    }

    return i;
}

